package com.lupan.tomcatStudy.mongodb.districtToBounds;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lupan.tomcatStudy.mongodb.districtToBounds.entity.City;
import com.lupan.tomcatStudy.mongodb.districtToBounds.entity.DistrictBounds;
import com.lupan.tomcatStudy.mongodb.districtToBounds.entity.Province;
import com.mongodb.BasicDBObject;
import com.timanetworks.foundation.common.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.geo.GeoJsonMultiPolygon;
import org.springframework.data.mongodb.core.geo.GeoJsonPolygon;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 说明：
 *
 * @author lupan
 * @version 2016/4/28 11:21
 */
@Service
public class ConvertService {

    @Autowired
    ConvertRepository convertRepository;

    String servicesRootUrl = "http://fotondev.timanetwork.com/dev/tm/";
    String securityKey = "2d3e04538ce7ec0a4b21851747eda121";
    String appKey = "3917230828";

    public List<Province> getAllProvince() {

        String interfaceUrl = "common-data/commonDataInternal/getProvinceList";
        String url = servicesRootUrl + interfaceUrl;
        Map<String, String> signParams = new HashMap<>();
        signParams.put("appkey", appKey);

        String response = HttpUtil.get(url + "?sign=" + HttpUtil.sign(interfaceUrl, signParams, securityKey) + "&appkey=" + appKey);
        JSONObject result = JSON.parseObject(response);
        return JSON.parseArray(JSON.toJSONString(result.get("commonDataList")), Province.class);
    }

    public List<City> getCitisByPrinviceName(String provinceName) {
        String interfaceUrl = "common-data/commonDataInternal/getCityList";
        String url = servicesRootUrl + interfaceUrl;
        Map<String, String> signParams = new HashMap<>();
        signParams.put("appkey", appKey);
        signParams.put("provinceName",provinceName);

        String response = null;
        try {
            response = HttpUtil.get(url + "?sign=" + HttpUtil.sign(interfaceUrl, signParams, securityKey) + "&appkey=" + appKey + "&provinceName=" + URLEncoder.encode(provinceName, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        JSONObject result = JSON.parseObject(response);
        return JSON.parseArray(JSON.toJSONString(result.get("commonDataList")), City.class);
    }

    public void saveBounds(String districtsJson,City city) {
        //区域对象可能有多个
        List<DistrictBounds> districtBoundsList = JSON.parseArray(districtsJson,DistrictBounds.class);
        if(districtBoundsList.size()>1){
            System.out.println(String.format("发现%s个区域对象",districtBoundsList.size()));
//            try {
//                throw new Exception("发现多个区域对象！");
//            } catch (Exception e) {
//                e.printStackTrace();
//                assert false:"发现多个区域对象!";
//            }
        }
        List<GeoJsonPolygon> polygons = new ArrayList<GeoJsonPolygon>();
        //解析边界点集合，可能只有一个区域对象但是以“|”区分不同区域
        for(DistrictBounds districtBounds:districtBoundsList){
            //可能有多个区域对象，但是有些对象无边界点
            if(StringUtils.isNotBlank(districtBounds.getPolyline())) {
                String[] boundsStrs = districtBounds.getPolyline().split("\\|");
                if (boundsStrs.length > 1) {
                    System.out.println(String.format("发现%s个区域|分界", boundsStrs.length));
                }
                for (String boundsStr : boundsStrs) {
                    List<Point> points = ConvertUtil.formatBounds(boundsStr);
                    GeoJsonPolygon geoJsonPolygon = new GeoJsonPolygon(points);
                    polygons.add(geoJsonPolygon);
                }
            }
        }

        GeoJsonMultiPolygon multiPolygon = new GeoJsonMultiPolygon(polygons);
        BasicDBObject basicDBObject = new BasicDBObject();
        basicDBObject.put("city", city.getCityName());
        basicDBObject.put("province", city.getProvince().getProvinceName());
        basicDBObject.put("cityCode", city.getCode());
        basicDBObject.put("provinceCode", city.getProvince().getCode());
        basicDBObject.put("loc", multiPolygon);

        convertRepository.save(basicDBObject, "places");

    }
}
